package com.pp.mariage.server;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * @author parant
 *
 */
public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String userName = request.getParameter("username");
		String password = request.getParameter("password");

		handleRequest(request, response, userName, password);
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String userName = request.getParameter("username");
		String password = request.getParameter("password");

		handleRequest(request, response, userName, password);
	}

	private void handleRequest(HttpServletRequest request,
			HttpServletResponse response, String userName, String password)
			throws IOException, ServletException {
		if ("aurelie".equals(userName) && "pascal".equals(password)) {
			request.getSession(true).setAttribute("username", "connected");
			response.sendRedirect("/restricted/main.jsp?id=0");
		} else if ("aurelie".equals(userName) && "admin".equals(password)) {
			request.getSession(true).setAttribute("username", "connected");
			request.getSession(true).setAttribute("admin", "true");
			response.sendRedirect("/restricted/main.jsp?id=0");
		} else {
			// erreur d'authentification
			request.setAttribute("messageError",
					"Login/Mot de passe incorrects");
			request.getRequestDispatcher("/index.jsp").forward(request,
					response);
		}
	}
}
